<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Session;
use Cookie;

class agentOrder extends BaseModel
{
    protected $table = "agent_order";

    const PREFIX = 'ag_';


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }


    public function addOrder($request)
    {
        $order_sn = $request['order_sn'];
        if(!$request['QueryKey']){
            return ['status' => 400, 'msg' => '请输入订单号'];
        }
        $order = []; // 订单数据
        $security = new Securitycodein();
        $goods = new Goods();
        $this->start();
        try {
            // 根据入库防伪码查找订单信息
            foreach ($order_sn as $k => $item) {
                $where['code'] = $item;
                $securityInfo = $security->getOne($where);
                $_tempOrder['mobile'] = $request['QueryKey'];
                // 判断商品是否存在
                $gwhere['id'] = $securityInfo['goods_id'];
                $goods->getOne($gwhere);
                $order[$securityInfo['goods_id']][] = $_tempOrder;
            }
            $inser = [];
            $key = 0;
            // 整理订单信息
            foreach ($order as $k => $v) {
                $inser[$key] = $v[0];
                $inser[$key]['order_sn'] = createOrderNo();
                $inser[$key]['num'] = count($v);
                $key++;
                $this->add($inser);
            }
            $this->commit();
            return ['status' => 200, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            $this->rollback();
            return ['status' => 400, 'msg' => '操作失败'];
        }

    }
}